<template>
  <div class="activities-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>活动公告管理</h1>
        <p>管理系统公告和活动信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="addActivity">
          <el-icon><Plus /></el-icon>
          发布公告
        </el-button>
        <el-button @click="refreshActivities">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="公告类型">
          <el-select v-model="filterForm.type" placeholder="选择类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="系统公告" value="system" />
            <el-option label="活动通知" value="activity" />
            <el-option label="维护通知" value="maintenance" />
            <el-option label="优惠活动" value="promotion" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="已下线" value="offline" />
          </el-select>
        </el-form-item>

        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索标题或内容"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchActivities">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 当前筛选条件显示 -->
      <div v-if="hasActiveFilters" class="active-filters">
        <span class="filter-label">当前筛选条件：</span>
        <el-tag
          v-if="filterForm.type"
          closable
          @close="clearFilter('type')"
          class="filter-tag"
        >
          公告类型：{{ getTypeText(filterForm.type) }}
        </el-tag>
        <el-tag
          v-if="filterForm.status"
          closable
          @close="clearFilter('status')"
          class="filter-tag"
        >
          状态：{{ getStatusText(filterForm.status) }}
        </el-tag>
        <el-tag
          v-if="filterForm.keyword"
          closable
          @close="clearFilter('keyword')"
          class="filter-tag"
        >
          关键词：{{ filterForm.keyword }}
        </el-tag>
      </div>
    </el-card>

    <!-- 公告列表 -->
    <el-card class="table-card">
      <el-table :data="filteredActivities" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" width="300" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.priority === 'high' ? 'danger' :
                     scope.row.priority === 'medium' ? 'warning' : 'info'"
            >
              {{ getPriorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="150">
          <template #default="scope">
            <span v-if="scope.row.publishTime">{{ formatTime(scope.row.publishTime) }}</span>
            <span v-else class="text-muted">未发布</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="activity-action-buttons">
              <el-button type="primary" size="small" @click="editActivity(scope.row)">
                编辑
              </el-button>
              <el-button
                v-if="scope.row.status === 'draft'"
                type="success"
                size="small"
                @click="publishActivity(scope.row)"
              >
                发布
              </el-button>
              <el-button
                v-if="scope.row.status === 'published'"
                type="warning"
                size="small"
                @click="offlineActivity(scope.row)"
              >
                下线
              </el-button>
              <el-button type="danger" size="small" @click="deleteActivity(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑公告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑公告' : '发布公告'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="activityForm" :rules="activityRules" ref="activityFormRef" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="activityForm.title" placeholder="请输入公告标题" />
        </el-form-item>

        <el-form-item label="公告类型" prop="type">
          <el-select v-model="activityForm.type" placeholder="请选择类型">
            <el-option label="系统公告" value="system" />
            <el-option label="活动通知" value="activity" />
            <el-option label="维护通知" value="maintenance" />
            <el-option label="优惠活动" value="promotion" />
          </el-select>
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-select v-model="activityForm.priority" placeholder="请选择优先级">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>

        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="activityForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          />
        </el-form-item>

        <el-form-item label="轮播图片">
          <div class="carousel-image-section">
            <el-upload
              class="carousel-upload"
              :show-file-list="false"
              :before-upload="beforeCarouselUpload"
              accept="image/*"
            >
              <div v-if="activityForm.carouselImage" class="carousel-preview">
                <img :src="activityForm.carouselImage" alt="轮播图预览" />
                <div class="carousel-overlay">
                  <el-button type="danger" size="small" @click.stop="removeCarouselImage">
                    删除
                  </el-button>
                </div>
              </div>
              <div v-else class="carousel-placeholder">
                <el-icon class="carousel-icon"><Plus /></el-icon>
                <div class="carousel-text">点击上传轮播图片</div>
                <div class="carousel-tip">建议尺寸：800x332px</div>
              </div>
            </el-upload>
            <div class="carousel-options">
              <el-checkbox v-model="activityForm.showInCarousel">
                在首页轮播图中显示
              </el-checkbox>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="activityForm.status">
            <el-radio label="draft">保存为草稿</el-radio>
            <el-radio label="published">立即发布</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="定时发布" v-if="activityForm.status === 'published'">
          <el-date-picker
            v-model="activityForm.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <div class="form-tip">不选择则立即发布</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveActivity" :loading="saving">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Refresh
} from '@element-plus/icons-vue';

export default {
  name: 'Activities',
  components: {
    Plus,
    Refresh
  },
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const isEdit = ref(false);
    const saving = ref(false);
    const activityFormRef = ref();

    // 筛选表单
    const filterForm = reactive({
      type: '',
      status: '',
      keyword: ''
    });

    // 公告数据
    const activities = ref([]);

    // 表单数据
    const activityForm = reactive({
      id: null,
      title: '',
      type: '',
      content: '',
      priority: 'medium',
      status: 'draft',
      publishTime: null,
      carouselImage: '',
      showInCarousel: false
    });

    // 表单验证规则
    const activityRules = {
      title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
      type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
      content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
    };

    // 计算属性
    const filteredActivities = computed(() => {
      let result = activities.value;

      if (filterForm.type) {
        result = result.filter(activity => activity.type === filterForm.type);
      }

      if (filterForm.status) {
        result = result.filter(activity => activity.status === filterForm.status);
      }

      if (filterForm.keyword) {
        const keyword = filterForm.keyword.toLowerCase();
        result = result.filter(activity =>
          activity.title.toLowerCase().includes(keyword) ||
          activity.content.toLowerCase().includes(keyword)
        );
      }

      return result;
    });

    // 是否有激活的筛选条件
    const hasActiveFilters = computed(() => {
      return filterForm.type || filterForm.status || filterForm.keyword;
    });

    // 方法
    const loadActivities = () => {
      loading.value = true;

      // 从本地存储获取公告数据
      const storedActivities = localStorage.getItem('activities');
      if (storedActivities) {
        activities.value = JSON.parse(storedActivities);
      } else {
        // 模拟初始数据
        activities.value = [
          {
            id: 1,
            title: '台球厅春节营业时间调整通知',
            type: 'system',
            content: '春节期间（2月10日-2月17日）营业时间调整为10:00-22:00，请各位顾客注意安排时间。',
            priority: 'high',
            status: 'published',
            publishTime: new Date().toISOString(),
            createTime: new Date().toISOString()
          },
          {
            id: 2,
            title: '新年优惠活动',
            type: 'promotion',
            content: '新年期间，所有台球桌8折优惠，活动时间：2月1日-2月29日。',
            priority: 'medium',
            status: 'published',
            publishTime: new Date().toISOString(),
            createTime: new Date().toISOString()
          }
        ];
        saveToLocalStorage();
      }

      loading.value = false;
    };

    const saveToLocalStorage = () => {
      localStorage.setItem('activities', JSON.stringify(activities.value));
    };

    const refreshActivities = () => {
      loadActivities();
      ElMessage.success('刷新成功');
    };

    const addActivity = () => {
      isEdit.value = false;
      Object.assign(activityForm, {
        id: null,
        title: '',
        type: '',
        content: '',
        priority: 'medium',
        status: 'draft',
        publishTime: null,
        carouselImage: '',
        showInCarousel: false
      });
      dialogVisible.value = true;
    };

    // 轮播图片上传前处理
    const beforeCarouselUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
        return false;
      }

      // 创建文件预览URL
      const reader = new FileReader();
      reader.onload = (e) => {
        activityForm.carouselImage = e.target.result;
      };
      reader.readAsDataURL(file);

      return false; // 阻止自动上传
    };

    // 删除轮播图片
    const removeCarouselImage = () => {
      activityForm.carouselImage = '';
      activityForm.showInCarousel = false;
    };

    const editActivity = (activity) => {
      isEdit.value = true;
      Object.assign(activityForm, { ...activity });
      dialogVisible.value = true;
    };

    const saveActivity = async () => {
      try {
        await activityFormRef.value.validate();
        saving.value = true;

        const now = new Date().toISOString();

        if (isEdit.value) {
          const index = activities.value.findIndex(a => a.id === activityForm.id);
          if (index !== -1) {
            activities.value[index] = {
              ...activityForm,
              publishTime: activityForm.status === 'published' ?
                (activityForm.publishTime || now) : null
            };
          }
          ElMessage.success('公告更新成功');
        } else {
          const newActivity = {
            ...activityForm,
            id: Math.max(...activities.value.map(a => a.id), 0) + 1,
            createTime: now,
            publishTime: activityForm.status === 'published' ?
              (activityForm.publishTime || now) : null
          };
          activities.value.unshift(newActivity);
          ElMessage.success('公告添加成功');
        }

        // 如果设置为轮播图显示，更新首页轮播图数据
        if (activityForm.showInCarousel && activityForm.carouselImage) {
          updateCarouselData();
        }

        saveToLocalStorage();
        dialogVisible.value = false;
      } catch (error) {
        console.error('保存失败:', error);
      } finally {
        saving.value = false;
      }
    };

    const publishActivity = async (activity) => {
      try {
        await ElMessageBox.confirm(`确认发布公告 "${activity.title}" 吗？`, '确认发布', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info'
        });

        const index = activities.value.findIndex(a => a.id === activity.id);
        if (index !== -1) {
          activities.value[index].status = 'published';
          activities.value[index].publishTime = new Date().toISOString();
        }

        saveToLocalStorage();
        ElMessage.success('公告发布成功');
      } catch (error) {
        // 用户取消
      }
    };

    const offlineActivity = async (activity) => {
      try {
        await ElMessageBox.confirm(`确认下线公告 "${activity.title}" 吗？`, '确认下线', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const index = activities.value.findIndex(a => a.id === activity.id);
        if (index !== -1) {
          activities.value[index].status = 'offline';
        }

        saveToLocalStorage();
        ElMessage.success('公告已下线');
      } catch (error) {
        // 用户取消
      }
    };

    const deleteActivity = async (activity) => {
      try {
        await ElMessageBox.confirm(`确认删除公告 "${activity.title}" 吗？`, '确认删除', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error'
        });

        const index = activities.value.findIndex(a => a.id === activity.id);
        if (index !== -1) {
          activities.value.splice(index, 1);
        }

        saveToLocalStorage();
        ElMessage.success('公告删除成功');
      } catch (error) {
        // 用户取消
      }
    };

    const searchActivities = () => {
      // 搜索逻辑已在计算属性中处理
    };

    const resetFilter = () => {
      filterForm.type = '';
      filterForm.status = '';
      filterForm.keyword = '';
    };

    // 清除单个筛选条件
    const clearFilter = (filterKey) => {
      filterForm[filterKey] = '';
    };

    // 辅助方法
    const getTypeText = (type) => {
      const typeMap = {
        system: '系统公告',
        activity: '活动通知',
        maintenance: '维护通知',
        promotion: '优惠活动'
      };
      return typeMap[type] || '未知';
    };

    const getTypeTagType = (type) => {
      const typeMap = {
        system: 'primary',
        activity: 'success',
        maintenance: 'warning',
        promotion: 'danger'
      };
      return typeMap[type] || 'info';
    };

    const getStatusText = (status) => {
      const statusMap = {
        published: '已发布',
        draft: '草稿',
        offline: '已下线'
      };
      return statusMap[status] || '未知';
    };

    const getStatusTagType = (status) => {
      const typeMap = {
        published: 'success',
        draft: 'info',
        offline: 'danger'
      };
      return typeMap[status] || 'info';
    };

    const getPriorityText = (priority) => {
      const priorityMap = {
        high: '高',
        medium: '中',
        low: '低'
      };
      return priorityMap[priority] || '中';
    };

    const formatTime = (timeStr) => {
      if (!timeStr) return '';
      return new Date(timeStr).toLocaleString('zh-CN');
    };

    // 更新首页轮播图数据
    const updateCarouselData = () => {
      const carouselActivities = activities.value.filter(activity =>
        activity.status === 'published' &&
        activity.showInCarousel &&
        activity.carouselImage
      );

      // 将轮播图数据保存到本地存储，供首页使用
      localStorage.setItem('carouselActivities', JSON.stringify(carouselActivities));
      ElMessage.success('轮播图数据已更新');
    };

    onMounted(() => {
      loadActivities();
    });

    return {
      loading,
      dialogVisible,
      isEdit,
      saving,
      activityFormRef,
      filterForm,
      activities,
      activityForm,
      activityRules,
      filteredActivities,
      hasActiveFilters,
      refreshActivities,
      addActivity,
      editActivity,
      saveActivity,
      publishActivity,
      offlineActivity,
      deleteActivity,
      searchActivities,
      resetFilter,
      clearFilter,
      getTypeText,
      getTypeTagType,
      getStatusText,
      getStatusTagType,
      getPriorityText,
      formatTime,
      beforeCarouselUpload,
      removeCarouselImage,
      updateCarouselData
    };
  }
};
</script>

<style scoped>
.activities-container {
  padding: 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #2c3e50;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 筛选卡片 */
.filter-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 12px;
}

/* 当前筛选条件显示 */
.active-filters {
  margin-top: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
  font-weight: 500;
}

.filter-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

/* 表格卡片 */
.table-card {
  border: none;
  border-radius: 12px;
}

.text-muted {
  color: #909399;
}

/* 活动操作按钮容器 */
.activity-action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 230px;
  overflow-x: auto;
  padding: 2px 0;
}

.activity-action-buttons::-webkit-scrollbar {
  height: 4px;
}

.activity-action-buttons::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.activity-action-buttons::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.activity-action-buttons::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.activity-action-buttons .el-button {
  flex-shrink: 0;
  margin: 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 轮播图片上传样式 */
.carousel-image-section {
  width: 100%;
}

.carousel-upload {
  width: 100%;
}

.carousel-preview {
  position: relative;
  width: 300px;
  height: 125px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #dcdfe6;
}

.carousel-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.carousel-preview:hover .carousel-overlay {
  opacity: 1;
}

.carousel-placeholder {
  width: 300px;
  height: 125px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.carousel-placeholder:hover {
  border-color: #409eff;
}

.carousel-icon {
  font-size: 28px;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.carousel-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.carousel-tip {
  color: #909399;
  font-size: 12px;
}

.carousel-options {
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .activities-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: flex-start;
  }
}
</style>
